package com.liuche.homechat.common.common.event.listener;

import com.liuche.homechat.common.common.enums.YNEnum;
import com.liuche.homechat.common.common.event.UserOnlineEvent;
import com.liuche.homechat.common.common.utils.IpUtil;
import com.liuche.homechat.common.user.dao.UserDao;
import com.liuche.homechat.common.user.domain.entity.User;
import com.liuche.homechat.common.websocket.service.CustomWebSocketService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * @author：liuche
 * @Date：2024年06月08日 14:19
 * @Description：
 */
@Slf4j
@Component
public class UserOnlineEventListener {
    @Resource
    private CustomWebSocketService customWebSocketService;

    @Resource
    private UserDao userDao;
    /**
     * 更新用户 IP 信息
     * @param event
     */
    @Async
    @EventListener(classes = UserOnlineEvent.class)
    public void refreshUserIpInfo(UserOnlineEvent event) {
        User user = event.getUser();
        log.info("refreshUserIpInfo -- user online info：：【{}】", user);
        // 更新用户状态信息及 IP 信息
        userDao.updateById(user);
        IpUtil.refreshUserIp(user);
    }

    /**
     * 实时更新在线用户列表
     * @param event
     */
    @Async
    @EventListener(classes = UserOnlineEvent.class)
    public void sendUserOnlineInfo(UserOnlineEvent event) {
        User user = event.getUser();
        log.info("refreshUserIpInfo -- user online info：：【{}】", user);

        customWebSocketService.noticeOnlineUsers(user);
    }
}
